package com.fudan.sys.security;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.fudan.sys.entity.User;
import com.fudan.sys.service.PermissionService;
import com.fudan.sys.service.UserService;

public class SysRealm extends AuthorizingRealm{

	@Autowired
	//@Lazy
	private UserService userService;
	
	@Autowired
	//@Lazy
	private PermissionService permissionService;

	//权限添加
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		String userName = String.valueOf(principals.getPrimaryPrincipal());
		User user = userService.getUserByName(userName);
		List<String> permissions = permissionService.findPermissionCodeByUser(user.getId());
		authorizationInfo.addStringPermissions(permissions);
		return authorizationInfo;
	}

	//用户认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		if(token.getPrincipal() == null) {
			return null;
		}
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String name = upToken.getUsername();
		String pwd = String.valueOf(upToken.getPassword());
		User user = userService.getUserByName(name);
		if(user == null) {
			throw new UnknownAccountException("不存在该用户");
		}
		String hashedPassword = PasswordUtils.encrypt(pwd);
		if(!hashedPassword.equals(user.getPassword())) {
			throw new IncorrectCredentialsException("密码错误");
		}
		//验证
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,hashedPassword,ByteSource.Util.bytes("lobster"),getName());
		return authenticationInfo;
	}

}
